import { defineNuxtPlugin } from '#app'
import type { Environment, ModuleConfig, APIConfig, EnvironmentConfig } from '~/utils/apiConfig'

export default defineNuxtPlugin((nuxtApp) => {
  const config = useRuntimeConfig()
  const GLOBAL_ENABLE_MOCK = config.public.GLOBAL_ENABLE_MOCK === 'true'

  // 默认配置
  const defaultConfig: EnvironmentConfig = {
    local: {
      freelancer: {
        baseURL: '/api/freelancer',
        useMock: false
      }
    },
    development: {
      freelancer: {
        baseURL: 'http://uni-backend:5200/api/freelancer',
        useMock: false
      }
    },
    production: {
      freelancer: {
        baseURL: 'https://api.leyepai.com/api/freelancer',
        useMock: false
      }
    }
  }

  let currentEnvironment: Environment = 'local'

  const setEnvironment = (env: Environment) => {
    currentEnvironment = env
  }

  const getConfig = (module: string): ModuleConfig => {
    return defaultConfig[currentEnvironment][module] || {
      baseURL: '',
      useMock: false
    }
  }

  const getCurrentEnvironment = (): Environment => {
    return currentEnvironment
  }

  // 将配置相关的函数提供给应用
  nuxtApp.provide('apiConfig', {
    setEnvironment,
    getConfig,
    getCurrentEnvironment,
    GLOBAL_ENABLE_MOCK
  })
})